using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Cupertino.Support.Views;

public class MagicStackPanel : StackPanel
{
    private SolidColorBrush color1 = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFFFFF"));
    private SolidColorBrush color2 = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#EEEEEE"));

    public double ItemHeight
    {
        get { return (double)GetValue(ItemHeightProperty); }
        set { SetValue(ItemHeightProperty, value); }
    }

    // Using a DependencyProperty as the backing store for ItemHeight.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ItemHeightProperty =
        DependencyProperty.Register("ItemHeight", typeof(double), typeof(MagicStackPanel), new PropertyMetadata(0.0, ItemHeightPropertyChanged));

    //ItemHeight属性跟TreeView的实际高度绑定，随着点开子层级，ActualHeight不断变化
    //进而触发回调，在回调中用高度除以单个高度36，得到行数，在向stackpanel交替添加不同背景颜色的border子元素
    //stackpanel和treeviewitem在同一个grid里面，stackpanel只是为了提供交替背景色
    private static void ItemHeightPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MagicStackPanel panel = (MagicStackPanel)d;
        panel.Children.Clear();
        panel.Height = panel.ItemHeight;

        int index = (int)panel.ItemHeight / 36;

        for (int i = 0; i < index; i++) 
        {
            Border border = new();
            border.Height = 36;
            border.Background = i % 2 == 0 ? panel.color1 : panel.color2;
            panel.Children.Add(border);
        }
    }
}